var fullData = null;

function getAllInfo(uid) {

    //发送异步请求
    jQuery.ajax({
        url: weibo_info + uid + ",0",
        type: "get",
        dataType: "json",
        contentType: "application/json;charset=utf-8"
    }).done(function (data) {
        loadWeiboTable(data.data.weibo);
        loadWeiboPublishTime(data.data.weibo);
        loadFormalData(data.data.weibo);
        loadWordCloud(data.data.weibo);
        loadSocialRelationsGraph(data.data.follow, data.data.userInfo);
        weiboEmotion(uid);


    }).fail(function (data) {
        layer.alert("请求失败", {icon: 7});
        layer.close(layerIndex);
    });

    //发送取全部数据的异步请求
    jQuery.ajax({
        url: weibo_info + uid + ",200",
        type: "get",
        dataType: "json",
        contentType: "application/json;charset=utf-8"
    }).done(function (data) {
        fullData = data;
        loadLevel1MapGraph();
    }).fail(function (data) {
        layer.alert("请求失败", {icon: 7});
        layer.close(layerIndex);
    });

}


/**
 * 加载用户微博表格
 * @param data
 */
function loadWeiboTable(data) {
    //排序后再fuzhi
    data.sort(compareByPublishTime);
    for (var i = 0; i < data.length; i++) {

        data[i].publish_time = timestampToTime(data[i].publish_time / 1000);

    }

    layui.use('table', function () {
        var table = layui.table;
        //展示已知数据
        table.render({
            elem: '#table_weibo'
            , cellMinWidth: 50 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
            , cols: [[ //标题栏
                {field: 'weibo_item_id', title: '微博ID', sort: true, align: 'center', width: 200}
                , {field: 'text', title: '微博内容', sort: true, align: 'center', minWidth: 600}
                , {field: 'publish_time', title: '发布时间', sort: true, align: 'center', minWidth: 50}
                , {field: 'devices', title: '发布设备', sort: true, align: 'center', minWidth: 40}
                , {field: 'upvote', title: '点赞数量', sort: true, align: 'center', minWidth: 40}
                , {field: 'repost', title: '转发数量', sort: true, align: 'center', minWidth: 40}
                , {field: 'is_resend', title: '是否原创', sort: true, align: 'center', minWidth: 40}
            ]]
            , data: data
            , skin: 'line' //表格风格
            , even: true
            , page: true //是否显示分页
            , limit: 13 //每页默认显示的数量
        });
    });

}

// 排序函数1,按发布时间排序
var compareByPublishTime = function (x, y) {//比较函数
    if (x.publish_time < y.publish_time) {
        return -1;
    } else if (x.publish_time > y.publish_time) {
        return 1;
    } else {
        return 0;
    }
}


/**
 * 微博发布时间的折线图，按年、月、日生成
 */
function loadWeiboPublishTime(data) {

    loadYear(data);
    loadMonth(data);
    loadDay(data);
    var yearChart;
    var monthChart;
    var dayChart;


    function loadYear(data) {
        //赋值给chart
        var thisChart = yearChart;
        //处理数据
        let yearSet = new Set();
        let yearMap = new Map();
        var yearArr = new Array();
        var yearData = data;
        var yearCount = new Array();
        var startYear = yearData[0].publish_time.substr(0, 4);
        var endYear = yearData[yearData.length - 1].publish_time.substr(0, 4);

        for (var i = 0; i < yearData.length; i++) {
            var year = yearData[i].publish_time.substr(0, 4);
            yearSet.add(year);
            if (yearMap.get(year) == undefined)
                yearMap.set(year, 1);
            else
                yearMap.set(year, (yearMap.get(year) + 1));
        }
        //动态生成年份
        for (var i = parseInt(startYear); i <= parseInt(endYear); i++) {
            if (yearMap.get(i + '') == undefined) {
                var obj = new Object();
                obj.year = i;
                obj.count = 0;
                yearCount.push(obj);
            }
            else {
                var obj = new Object();
                obj.year = i;
                obj.count = yearMap.get(i + '');
                yearCount.push(obj);
            }
        }
        //排序
        yearCount.sort(compareByStr);

        // 基于准备好的dom，初始化ECharts实例
        if (thisChart != null && thisChart != "" && thisChart != undefined) {
            thisChart.dispose();
        }
        thisChart = echarts.init(document.getElementById('div_year_line'), 'macarons');
        thisChart.showLoading();
        var option = {
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                data: ['最高']
            },
            toolbox: {
                show: true,
                feature: {
                    mark: {show: true},
                    dataZoom: {show: true},
                    dataView: {show: true},
                    magicType: {show: true, type: ['line', 'bar', 'stack', 'tiled']},
                    restore: {show: true},
                    saveAsImage: {show: true}
                }
            },
            calculable: true,
            dataZoom: {
                show: true,
                realtime: true,
                start: 20,
                end: 80
            },
            xAxis: [
                {
                    type: 'category',
                    boundaryGap: false,
                    data: function () {
                        var list = [];
                        for (var i = 0; i < yearCount.length; i++) {
                            list.push(yearCount[i].year);
                        }
                        return list;
                    }()
                }
            ],
            yAxis: [
                {
                    type: 'value'
                }
            ],
            series: [
                {
                    name: '年活跃',
                    type: 'line',
                    data: function () {
                        var list = [];
                        for (var i = 0; i < yearCount.length; i++) {
                            list.push(yearCount[i].count);
                        }
                        return list;
                    }()
                }
            ]
        };
        thisChart.hideLoading();
        thisChart.setOption(option, true);


    }

    function loadMonth(data) {

        //赋值给chart
        var thisChart = monthChart;
        //处理数据
        let monthMap = new Map();
        var monthArr = new Array();
        var monthData = data;
        var monthCount = new Array();
        var startMonth = monthData[0].publish_time.substr(0, 7);
        var endMonth = monthData[monthData.length - 1].publish_time.substr(0, 7);

        for (var i = 0; i < monthData.length; i++) {
            var month = monthData[i].publish_time.substr(0, 7);
            if (monthMap.get(month) == undefined)
                monthMap.set(month, 1);
            else
                monthMap.set(month, (monthMap.get(month) + 1));
        }

        var startMonthArr = startMonth.split('-');
        var endMonthArr = endMonth.split('-');
        var sub = (parseInt(endMonthArr[0]) - parseInt(startMonthArr[0])) * 12 + (parseInt(endMonthArr[1]) - parseInt(startMonthArr[1]));
        var y = parseInt(monthData[0].publish_time.substr(0, 4));
        var m = parseInt(monthData[0].publish_time.substr(6, 7));
        for (var i = 0; i < sub; i++) {
            if (m > 12) {
                m = 1;
                y++;
            }
            var m_str = m < 10 ? '0' + m + '' : m;
            var mon_str = y + "-" + m_str;
            if (monthMap.get(mon_str) == undefined) {
                var obj = new Object();
                obj.month = mon_str;
                obj.count = 0;
                monthCount.push(obj);
            }
            else {
                var obj = new Object();
                obj.month = mon_str;
                obj.count = monthMap.get(mon_str);
                monthCount.push(obj);
            }
            m++;
        }


        monthCount.sort(compareByMonth);

        // 基于准备好的dom，初始化ECharts实例
        if (thisChart != null && thisChart != "" && thisChart != undefined) {
            thisChart.dispose();
        }
        thisChart = echarts.init(document.getElementById('div_month_line'), 'macarons');
        thisChart.showLoading();
        var option = {
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                data: ['月活跃']
            },
            toolbox: {
                show: true,
                feature: {
                    mark: {show: true},
                    dataZoom: {show: true},
                    dataView: {show: true},
                    magicType: {show: true, type: ['line', 'bar', 'stack', 'tiled']},
                    restore: {show: true},
                    saveAsImage: {show: true}
                }
            },
            calculable: true,
            dataZoom: {
                show: true,
                realtime: true,
                start: 20,
                end: 80
            },
            xAxis: [
                {
                    type: 'category',
                    boundaryGap: false,
                    data: function () {
                        var list = [];
                        for (var i = 0; i < monthCount.length; i++) {
                            list.push(monthCount[i].month);
                        }
                        return list;
                    }()
                }
            ],
            yAxis: [
                {
                    type: 'value'
                }
            ],
            series: [
                {
                    name: '月活跃',
                    type: 'line',
                    data: function () {
                        var list = [];
                        for (var i = 0; i < monthCount.length; i++) {
                            list.push(monthCount[i].count);
                        }
                        return list;
                    }()
                }
            ]
        };
        thisChart.hideLoading();
        thisChart.setOption(option, true);

    }

    function loadDay(data) {

        //赋值给chart
        var thisChart = dayChart;
        //处理数据
        let dayMap = new Map();
        var dayArr = new Array();
        var dayData = data;
        var dayCount = new Array();
        //先把已有的数据放进map中
        for (var i = 0; i < dayData.length; i++) {
            var day = dayData[i].publish_time;
            if (dayMap.get(day) == undefined)
                dayMap.set(day, 1);
            else
                dayMap.set(day, (dayMap.get(day) + 1));
        }
        //再动态生成全部的日期
        var startDay = dayData[0].publish_time;
        var endDay = dayData[dayData.length - 1].publish_time;
        var len = datedifference(startDay, endDay);
        for (var i = 0; i < len; i++) {
            var date = new Date(startDay);
            date.setDate(date.getDate() + i);
            var month = date.getMonth() + 1;
            var day = date.getDate();
            var finDay = date.getFullYear() + '-' + getFormatDate(month) + '-' + getFormatDate(day);
            if (dayMap.get(finDay) == undefined) {
                var obj = new Object();
                obj.day = finDay;
                obj.count = 0;
                dayCount.push(obj);
            }
            else {
                var obj = new Object();
                obj.day = finDay;
                obj.count = dayMap.get(finDay);
                dayCount.push(obj);
            }

        }


        // 基于准备好的dom，初始化ECharts实例
        if (thisChart != null && thisChart != "" && thisChart != undefined) {
            thisChart.dispose();
        }
        thisChart = echarts.init(document.getElementById('div_day_line'), 'macarons');
        thisChart.showLoading();
        var option = {
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                data: ['日活跃']
            },
            toolbox: {
                show: true,
                feature: {
                    mark: {show: true},
                    dataZoom: {show: true},
                    dataView: {show: true},
                    magicType: {show: true, type: ['line', 'bar', 'stack', 'tiled']},
                    restore: {show: true},
                    saveAsImage: {show: true}
                }
            },
            calculable: true,
            dataZoom: {
                show: true,
                realtime: true,
                start: 20,
                end: 80
            },
            xAxis: [
                {
                    type: 'category',
                    boundaryGap: false,
                    data: function () {
                        var list = [];
                        for (var i = 0; i < dayCount.length; i++) {
                            list.push(dayCount[i].day);
                        }
                        return list;
                    }()
                }
            ],
            yAxis: [
                {
                    type: 'value'
                }
            ],
            series: [
                {
                    name: '日活跃',
                    type: 'line',
                    data: function () {
                        var list = [];
                        for (var i = 0; i < dayCount.length; i++) {
                            list.push(dayCount[i].count);
                        }
                        return list;
                    }()
                }
            ]
        };
        thisChart.hideLoading();
        thisChart.setOption(option, true);


        // 日期月份/天的显示，如果是1位数，则在前面加上'0'
        function getFormatDate(arg) {
            if (arg == undefined || arg == '') {
                return '';
            }

            var re = arg + '';
            if (re.length < 2) {
                re = '0' + re;
            }

            return re;
        }


    }

// 排序函数2,按发布时间排序
    var compareByStr = function (x, y) {//比较函数
        if (x.year < y.year) {
            return -1;
        } else if (x.year > y.year) {
            return 1;
        } else {
            return 0;
        }
    }

// 排序函数3,按发布时间排序
    var compareByMonth = function (x, y) {//比较函数
        if (x.month < y.month) {
            return -1;
        } else if (x.month > y.month) {
            return 1;
        } else {
            return 0;
        }
    }
}


/**
 * 微博附带的数据爬虫
 * @param data
 */
function loadFormalData(data) {


    loadDevicesPie(data);
    loadUpvotePie(data);
    loadRepostPie(data);
    var repostChart;
    var upvotePieChart;
    var devicesChart;


    /**
     * 转发与原创对比图
     * @param data
     */
    function loadRepostPie(data) {

        //赋值给chart
        var thisChart = repostChart;
        //处理数据
        let monthMap = new Map();
        var monthData = data;
        var timeLineLab = [];
        var options = [];
        //构建数据
        for (var i = 0; i < monthData.length; i++) {
            var month = monthData[i].publish_time.substr(0, 7);
            if (monthMap.get(month) == undefined) {
                var obj = new Object();
                obj.month = month;
                if (monthData[i].is_resend == "否") {
                    obj.repost = 1;
                    obj.self = 0;
                }
                else {
                    obj.self = 1;
                    obj.repost = 0;
                }
                monthMap.set(month, obj);
            }
            else {
                var obj = new Object();
                obj.month = month;
                if (monthData[i].is_resend == "否") {
                    obj.repost = (monthMap.get(month).repost + 1);
                    obj.self = (monthMap.get(month).self);
                }
                else {
                    obj.repost = (monthMap.get(month).repost);
                    obj.self = (monthMap.get(month).self + 1);
                }
                monthMap.set(month, obj);
            }
        }
        //构建时间轴以及饼图的数据
        for (var [key, value] of monthMap) {
            var keyObj = new Object();
            keyObj.value = key;
            keyObj.symbol = "diamond";
            keyObj.symbolSize = 16;
            timeLineLab.push(keyObj);

            var serialArr = new Object();
            var serials = new Array();
            var serialObj = new Object();
            serialObj.name = key + " 转发/原创 饼图";
            serialObj.type = "pie";
            serialObj.center = ['50%', '45%'];
            serialObj.radius = '50%';
            var dataArr = [];
            var repostObj = new Object();
            repostObj.value = value.repost;
            repostObj.name = '转发';
            var selfObj = new Object();
            selfObj.value = value.self;
            selfObj.name = '原创';
            dataArr.push(repostObj);
            dataArr.push(selfObj);
            serialObj.data = dataArr;
            serials.push(serialObj);
            var sobj = new Object();
            sobj.series = serials;
            options.push(sobj);


        }

        timeLineLab.sort(function (x, y) {//比较函数
            if (x.value < y.value) {
                return -1;
            } else if (x.value > y.value) {
                return 1;
            } else {
                return 0;
            }
        });
        options.sort(function (x, y) {//比较函数
            if (x.series[0].name < y.series[0].name) {
                return -1;
            } else if (x.series[0].name > y.series[0].name) {
                return 1;
            } else {
                return 0;
            }
        });

        options[0].title = {
            text: '转发与原创微博',
            subtext: '可了解博主的是否更喜欢创作还是更喜欢分享'
        };
        options[0].tooltip = {
            trigger: 'item',
            formatter: "{a} <br/>{b} : {c} ({d}%)"
        };
        options[0].legend = {
            data: ['原创', '转发']
        };
        options[0].toolbox = {
            show: true,
            feature: {
                mark: {show: true},
                dataView: {show: true, readOnly: false},
                magicType: {
                    show: true,
                    type: ['pie', 'funnel'],
                    option: {
                        funnel: {
                            x: '25%',
                            width: '50%',
                            funnelAlign: 'left',
                            max: 1700
                        }
                    }
                },
                restore: {show: true},
                saveAsImage: {show: true}
            }
        };


        // 基于准备好的dom，初始化ECharts实例
        if (thisChart != null && thisChart != "" && thisChart != undefined) {
            thisChart.dispose();
        }
        thisChart = echarts.init(document.getElementById('div_self_repost_line'), 'macarons');
        thisChart.showLoading();

        var option = {
                timeline: {
                    data: timeLineLab,
                    label: {},
                    axisType: 'category'
                },
                options: options
            }
        ;
        thisChart.hideLoading();
        thisChart.setOption(option, true);
    }


    /**
     * 被点赞与被转发的对比图
     * @param data
     */
    function loadUpvotePie(data) {

        //赋值给chart
        var thisChart = upvotePieChart;
        //处理数据
        let monthMap = new Map();
        var monthData = data;
        var timeLineLab = [];
        var options = [];
        //构建数据
        for (var i = 0; i < monthData.length; i++) {
            var month = monthData[i].publish_time.substr(0, 7);
            if (monthMap.get(month) == undefined) {
                var obj = new Object();
                obj.month = month;
                obj.upvote = monthData[i].upvote;
                obj.repost = monthData[i].repost;

                monthMap.set(month, obj);
            }
            else {
                var obj = new Object();
                obj.month = month;
                obj.repost = (monthMap.get(month).repost + monthData[i].repost);
                obj.upvote = (monthMap.get(month).upvote + monthData[i].upvote);
                monthMap.set(month, obj);
            }
        }
        //构建时间轴以及饼图的数据
        for (var [key, value] of monthMap) {
            var keyObj = new Object();
            keyObj.value = key;
            keyObj.symbol = "diamond";
            keyObj.symbolSize = 16;
            timeLineLab.push(keyObj);

            var serialArr = new Object();
            var serials = new Array();
            var serialObj = new Object();
            serialObj.name = key + " 点赞/转发 饼图";
            serialObj.type = "pie";
            serialObj.center = ['50%', '45%'];
            serialObj.radius = '50%';
            var dataArr = [];
            var repostObj = new Object();
            repostObj.value = value.repost;
            repostObj.name = '转发';
            var selfObj = new Object();
            selfObj.value = value.upvote;
            selfObj.name = '点赞';
            dataArr.push(repostObj);
            dataArr.push(selfObj);
            serialObj.data = dataArr;
            serials.push(serialObj);
            var sobj = new Object();
            sobj.series = serials;
            options.push(sobj);


        }

        timeLineLab.sort(function (x, y) {//比较函数
            if (x.value < y.value) {
                return -1;
            } else if (x.value > y.value) {
                return 1;
            } else {
                return 0;
            }
        });
        options.sort(function (x, y) {//比较函数
            if (x.series[0].name < y.series[0].name) {
                return -1;
            } else if (x.series[0].name > y.series[0].name) {
                return 1;
            } else {
                return 0;
            }
        });

        options[0].title = {
            text: '被点赞与被转发',
            subtext: '可了解博主的微博热度，点赞数应该都会略大于转发数'
        };
        options[0].tooltip = {
            trigger: 'item',
            formatter: "{a} <br/>{b} : {c} ({d}%)"
        };
        options[0].legend = {
            data: ['点赞', '转发']
        };
        options[0].toolbox = {
            show: true,
            feature: {
                mark: {show: true},
                dataView: {show: true, readOnly: false},
                magicType: {
                    show: true,
                    type: ['pie', 'funnel'],
                    option: {
                        funnel: {
                            x: '25%',
                            width: '50%',
                            funnelAlign: 'left',
                            max: 1700
                        }
                    }
                },
                restore: {show: true},
                saveAsImage: {show: true}
            }
        };


        // 基于准备好的dom，初始化ECharts实例
        if (thisChart != null && thisChart != "" && thisChart != undefined) {
            thisChart.dispose();
        }
        thisChart = echarts.init(document.getElementById('div_repost_upvote_line'), 'macarons');
        thisChart.showLoading();

        var option = {
                timeline: {
                    data: timeLineLab,
                    label: {},
                    axisType: 'category'
                },
                options: options
            }
        ;
        thisChart.hideLoading();
        thisChart.setOption(option, true);

    }


    function loadDevicesPie(data) {

        //赋值给chart
        var thisChart = devicesChart;
        //处理数据
        var devicesData = data;
        var devicesMap = new Map();
        var legend = [];
        var devicesArr = [];
        //构建数据
        for (var i = 0; i < devicesData.length; i++) {
            if (devicesMap.get(devicesData[i].devices) == undefined) {
                devicesMap.set(devicesData[i].devices, 1);
            }
            else {

                devicesMap.set(devicesData[i].devices, (devicesMap.get(devicesData[i].devices) + 1));
            }
        }
        for (var [key, value] of devicesMap) {
            legend.push(key);
            var obj = new Object();
            obj.value = value;
            obj.name = key;
            devicesArr.push(obj);
        }


        // 基于准备好的dom，初始化ECharts实例
        if (thisChart != null && thisChart != "" && thisChart != undefined) {
            thisChart.dispose();
        }
        thisChart = echarts.init(document.getElementById('div_devices_line'), 'macarons');
        thisChart.showLoading();

        var option = {
            title: {
                text: '用户发布微博设备统计饼图',
                subtext: '可以了解用户更倾向于使用哪类设备来进行浏览或者发布微博',
                x: 'left'
            },
            tooltip: {
                trigger: 'item',
                // formatter: "{a} <br/>{b} : {c} ({d}%)"
            },
            legend: {
                x: 'center',
                y: 'bottom',
                data: legend
            },
            toolbox: {
                show: true,
                feature: {
                    mark: {show: true},
                    dataView: {show: true, readOnly: false},
                    magicType: {
                        show: true,
                        type: ['pie', 'funnel']
                    },
                    restore: {show: true},
                    saveAsImage: {show: true}
                }
            },
            calculable: true,
            series: [
                {
                    name: '半径模式',
                    type: 'pie',
                    radius: [20, 110],
                    center: ['50%', '50%'],
                    roseType: 'radius',
                    label: {
                        normal: {
                            show: true
                        },
                        emphasis: {
                            show: true
                        }
                    },
                    lableLine: {
                        normal: {
                            show: true
                        },
                        emphasis: {
                            show: true
                        }
                    },
                    data: devicesArr
                }
            ]
        };
        thisChart.hideLoading();
        thisChart.setOption(option, true);

    }

}


/**
 * 加载微博的词云部分
 * @param data
 */
function loadWordCloud(data) {

    //拼接微博，调用词云接口
    var allWeiboStr;
    for (var i = 0; i < data.length; i++) {

        allWeiboStr += data[i].text + "。";

    }
    var requestObj = new Object();
    // requestObj.type = 'CIRCLE';
    requestObj.width = 500;
    requestObj.height = 500;
    requestObj.color = "#f5f2f0";
    requestObj.font = "MIRCOSOFT YA HEI";
    requestObj.text = allWeiboStr;
    var requestJson = JSON.stringify(requestObj);

    //发送异步请求
    jQuery.ajax({
        url: discourse_wordcloud_path,
        type: "post",
        data: requestJson,
        dataType: "json",
        contentType: "application/json;charset=utf-8"
    }).done(function (data) {

        $('#div_wordcloud_line').empty();
        $('#div_wordcloud_line').append("<img src=\"" + data.data.src + "\" title=\"\" style='margin-top: 60px;'>");


    }).fail(function (data) {
        layer.alert("请求失败", {icon: 7});
        layer.close(layerIndex);
    });

}


/**
 * 加载社交网络图
 */
function loadSocialRelationsGraph(listData, userData) {

    loadLevel1SocialGraph(listData, userData);
    // loadLevel2SocialGraph(listData, userData);
    // loadLevel1MapGraph(listData, userData);

    var socialLevel1Chart;
    var socialLevel2Chart;
    var socialLevel2Map;


    /**
     * 加载1层的社交网络图
     * @param data
     */
    function loadLevel1SocialGraph(listData, userData) {

        //赋值给chart
        var thisChart = socialLevel1Chart;
        //处理数据
        var copyArr = listData;//浅复制
        var nodeOfUser = [];
        var links = [];
        //对第一层的数据进行实例成点
        for (var i = 0; i < copyArr.length; i++) {
            var obj = new Object();
            obj.name = copyArr[i].name;
            obj.x = 1;
            obj.y = 1;
            obj.value = copyArr[i].follower_count;
            if (copyArr[i].gender == 'f')
                obj.category = '女';
            else
                obj.category = '男';
            obj.symbol = 'image://' + copyArr[i].image;
            // obj.symbol = 'circle';
            obj.symbolSize = 30;
            nodeOfUser.push(obj);
        }
        //先将查询的博主作为根结点
        var rootNode = new Object();
        rootNode.name = userData.name;
        rootNode.x = 1;
        rootNode.y = 1;
        rootNode.fixed = true;
        rootNode.value = userData.follower_count;
        if (userData.gender == 'f')
            rootNode.category = '女';
        else
            rootNode.category = '男';
        rootNode.symbol = 'image://' + userData.image;
        // rootNode.symbol = 'circle';
        rootNode.symbolSize = 30;
        nodeOfUser.push(rootNode);
        //构建节点的边
        for (var i = 0; i < copyArr.length; i++) {
            var link = new Object();
            link.source = nodeOfUser[i].name;
            link.target = rootNode.name;
            links.push(link);
        }


        // 基于准备好的dom，初始化ECharts实例
        if (thisChart != null && thisChart != "" && thisChart != undefined) {
            thisChart.dispose();
        }
        thisChart = echarts.init(document.getElementById('div_level_1_force'), 'macarons');
        thisChart.showLoading();


        var categories = [{name: "男"}, {name: "女"}];
        var option = {
                title: {
                    text: '单层图',
                    subtext: '由于微博系统本身的限制，至多只能收集200个关注用户的数据，因此希望在有限的数据中，得出有趣的结论。',
                    top: 'bottom',
                    left: 'right'
                },
                tooltip: {},
                legend: {
                    type: 'scroll',
                    orient: 'vertical',
                    right: 10,
                    top: 20,
                    bottom: 40,
                    data: categories
                },

                animation: true,
                series: [
                    {
                        name: '博主',
                        type: 'graph',
                        layout: 'force',
                        data: nodeOfUser,
                        links: links,
                        categories: categories,
                        focusNodeAdjacency: true,
                        roam: true,
                        lineStyle: {
                            normal: {
                                width: 0.5,
                                curveness: 0.3,
                                opacity: 0.7
                            }
                        },
                        label: {
                            show: false,
                            position: 'bottom'

                        },
                        force: {
                            repulsion: 0.05,
                            gravity: 6.3,
                            edgeLength: [5, 10],
                            layoutAnimation: false
                        },
                        tooltip: {}
                    }
                ]
            }
        ;

        thisChart.setOption(option);
        thisChart.hideLoading();

    }


}

/**
 * 获取粉丝size的大小
 * @param follower_count
 */
function getWeiboUserSize(follower_count) {
    follower_count = Math.sqrt(follower_count);
    if (follower_count > 10000)
        return 50;
    else if (follower_count < 100) {
        return 1;
    }
    else {
        return follower_count / 100;
    }
}


var socialLevel2Chart;
var socialLevel2Map;

$('#btn_render').click(
    /**
     * 第二层关注的
     * @param listData
     * @param userData
     */
    function loadLevel2SocialGraph() {

        var listData = fullData.data.follow, userData = fullData.data.userInfo;

        // //赋值给chart
        // var thisChart = socialLevel2Chart;
        // //处理数据
        // var copyArr = listData;//浅复制
        // var nodeOfUser = [];
        // var links = [];
        // // let nodeMap = new Map();
        // let nodeSet = new Set();
        //
        // //先将查询的博主作为根结点
        // var rootNode = new Object();
        // rootNode.name = userData.name;
        // rootNode.x = 1;
        // rootNode.y = 1;
        // rootNode.fixed = true;
        // rootNode.value = userData.follower_count;
        // if (userData.gender == 'f')
        //     rootNode.category = '女';
        // else
        //     rootNode.category = '男';
        // rootNode.symbol = 'image://' + userData.image;
        // // rootNode.symbol = 'circle';
        // rootNode.symbolSize = 30;
        // nodeOfUser.push(rootNode);
        // nodeSet.add(rootNode.name);
        //
        // //对第一层的数据进行实例成点
        // for (var i = 0; i < copyArr.length; i++) {
        //     var obj = new Object();
        //     obj.name = copyArr[i].name;
        //     obj.x = 1;
        //     obj.y = 1;
        //     obj.value = copyArr[i].follower_count;
        //     if (copyArr[i].gender == 'f')
        //         obj.category = '女';
        //     else
        //         obj.category = '男';
        //     // obj.symbol = 'image://' + copyArr[i].image;
        //     // obj.symbol = 'circle';
        //     obj.symbolSize = getWeiboUserSize(copyArr[i].follower_count);
        //     if (nodeSet.has(copyArr[i].name)) {
        //
        //     }
        //     else {
        //         nodeSet.add(copyArr[i].name);
        //         nodeOfUser.push(obj);
        //     }
        //
        //     //内层循环
        //     for (var j = 0; j < copyArr[i].follow.length; j++) {
        //         var obj = new Object();
        //         obj.name = copyArr[i].follow[j].name;
        //         obj.x = 1;
        //         obj.y = 1;
        //         obj.value = copyArr[i].follow[j].follower_count;
        //         if (copyArr[i].follow[j].gender == 'f')
        //             obj.category = '女';
        //         else
        //             obj.category = '男';
        //         // obj.symbol = 'image://' + copyArr[i].follow[j].image;
        //         // obj.symbol = 'circle';
        //         obj.symbolSize = getWeiboUserSize(copyArr[i].follow[j].follower_count);
        //         if (nodeSet.has(copyArr[i].follow[j].name)) {
        //
        //         }
        //         else {
        //             nodeSet.add(copyArr[i].follow[j].name);
        //             nodeOfUser.push(obj);
        //         }
        //
        //         console.log("i=" + i + "   j=" + j);
        //     }
        //
        // }
        //
        // // //构建节点的边
        // let tmpMap = new Map();
        // for (var i = 0; i < copyArr.length; i++) {
        //     // if (tmpMap.get(copyArr[i].name + rootNode.name) == undefined && tmpMap.get(rootNode.name + copyArr[i].name) == undefined) {
        //     var link = new Object();
        //     link.target = copyArr[i].name;
        //     link.source = rootNode.name;
        //     tmpMap.set(link.target + link.source, true);
        //     links.push(link);
        //     // }
        //     for (var j = 0; j < copyArr[i].follow.length; j++) {
        //         // if (tmpMap.get(copyArr[i].follow[j].name + copyArr[i].name) == undefined && tmpMap.get(copyArr[i].name + copyArr[i].follow[j].name) == undefined) {
        //         var link = new Object();
        //         link.target = copyArr[i].follow[j].name;
        //         link.source = copyArr[i].name;
        //         tmpMap.set(link.target + link.source, true);
        //         links.push(link);
        //         // }
        //     }
        // }
        //
        // // 基于准备好的dom，初始化ECharts实例
        // if (thisChart != null && thisChart != "" && thisChart != undefined) {
        //     thisChart.dispose();
        // }
        // thisChart = echarts.init(document.getElementById('div_level_2_force'), 'macarons');
        // thisChart.showLoading();
        //
        //
        // var categories = [{name: "男"}, {name: "女"}];
        // var option = {
        //         title: {
        //             text: '单层图',
        //             subtext: '由于微博系统本身的限制，至多只能收集200个关注用户的数据，因此希望在有限的数据中，得出有趣的结论。',
        //             top: 'top',
        //             left: 'right'
        //         },
        //         tooltip: {},
        //         legend: {
        //             type: 'scroll',
        //             orient: 'vertical',
        //             right: 10,
        //             top: 20,
        //             bottom: 40,
        //             data: categories
        //         },
        //
        //         animation: true,
        //         series: [
        //             {
        //                 name: '博主',
        //                 type: 'graph',
        //                 layout: 'force',
        //                 data: nodeOfUser,
        //                 links: links,
        //                 categories: categories,
        //                 focusNodeAdjacency: true,
        //                 roam: true,
        //                 lineStyle: {
        //                     normal: {
        //                         width: 0.5,
        //                         curveness: 0.3,
        //                         opacity: 0.7
        //                     }
        //                 },
        //                 label: {
        //                     show: false,
        //                     position: 'bottom'
        //
        //                 },
        //                 force: {
        //                     repulsion: 0.3,
        //                     gravity: 3,
        //                     edgeLength: [5, 10],
        //                     layoutAnimation: false
        //                 },
        //                 tooltip: {}
        //             }
        //         ]
        //     }
        // ;
        //
        // thisChart.setOption(option);
        // thisChart.hideLoading();

        var index = layer.open({
            type: 1,
            content: ' <div id="div_level_2_force" style="width: 1920px;height:1080px;"></div>',
            area: ['1366px', '768px'],
            maxmin: true
        });

        //赋值给chart
        var thisChart = socialLevel2Chart;
        //处理数据
        var copyArr = listData;//浅复制
        var nodeOfUser = [];
        var links = [];
        let nodeSet = new Set();
        var categories = [];
        var color = ['#F012BE', '#00DBE7', '#01AAC1', '#00649F', '#EF255F', '#FCCF4D', '#49BEB7', '#085F63', '#476268', '#40A798', '#F1F1F1', '#F5E1DA', '#FFBDD4', '#FF5C5C', '#FFC77F', '#FFE5B9', '#583131', '#FC6E5E', '#E3F3F7', '#B0DEDB', '#AC005D', '#F85959', '#FF9F68', '#FEFF89', '#8785A2', '#F6F6F6', '#FFE2E2', '#FFC7C7', '#F8B195', '#F67280', '#C06C84', '#6C567B', '#FCE38A', '#02C39A', '#028090', '#003459', '#756C83', '#F38181', '#B9E1DC', '#FBFBFB', '#539092', '#8BCFCC', '#AEE8E6', '#F5FAC8', '#4756CA', '#3186B2', '#0FC9E7', '#FCFCFC', '#3F7B70', '#265A5C', '#113C4A', '#DDDDDD', '#F2BBBB', '#ED93CB', '#CA82F8', '#A1D9FF', '#FF851B', '#FF4136', '#85144b', '#97ECC5', '#B10DC9', '#111111', '#AAAAAA', '#DDDDDD', "rgb(203,239,15)", "rgb(73,15,239)", "rgb(239,231,15)", "rgb(15,217,239)", "rgb(30,15,239)", "rgb(15,174,239)", "rgb(116,239,15)", "rgb(239,15,58)", "rgb(15,239,174)", "rgb(239,102,15)", "rgb(239,15,15)", "rgb(15,44,239)", "rgb(239,145,15)", "rgb(30,239,15)", "rgb(239,188,15)", "rgb(159,239,15)", "rgb(159,15,239)", "rgb(15,239,44)", "rgb(15,239,87)", "rgb(15,239,217)", "rgb(203,15,239)", "rgb(239,15,188)", "rgb(239,15,102)", "rgb(239,58,15)", "rgb(239,15,145)", "rgb(116,15,239)", "rgb(15,131,239)", "rgb(73,239,15)", "rgb(15,239,131)", "rgb(15,87,239)", "rgb(239,15,231"];
        //处理数据
        //先将查询的博主作为根结点
        var rootNode = new Object();
        rootNode.name = userData.name;
        rootNode.x = 1;
        rootNode.y = 1;
        rootNode.fixed = true;
        rootNode.value = userData.follower_count;
        rootNode.category = userData.name;
        rootNode.symbolSize = 50;
        rootNode.itemStyle = {
            color: '#f00',
            opacity: 1
        };
        nodeOfUser.push(rootNode);
        nodeSet.add(rootNode.name);
        categories.push(rootNode.name);

        for (var i = 0; i < copyArr.length; i++) {
            var link = new Object();
            link.target = copyArr[i].name;
            link.source = rootNode.name;
            link.value = 2;
            links.push(link);
            for (var j = 0; j < copyArr[i].follow.length; j++) {
                var link = new Object();
                link.target = copyArr[i].follow[j].name;
                link.source = copyArr[i].name;
                link.value = 2;
                links.push(link);
            }
        }

        //对第一层的数据进行实例成点
        for (var i = 0; i < copyArr.length; i++) {
            var obj = new Object();
            obj.name = copyArr[i].name;
            obj.x = Math.random() * window.innerWidth;
            obj.y = Math.random() * window.innerHeight;
            obj.value = copyArr[i].follower_count;
            obj.symbolSize = getWeiboUserSize(copyArr[i].follower_count);
            obj.category = rootNode.name;
            obj.itemStyle = {
                color: '#000000',
                opacity: 0.8
            };
            if (nodeSet.has(copyArr[i].name)) {

            }
            else {
                // categories.push(copyArr[i].name);
                categories.push(copyArr[i].name);
                nodeSet.add(copyArr[i].name);
                nodeOfUser.push(obj);
            }

            //内层循环
            for (var j = 0; j < copyArr[i].follow.length; j++) {
                var obj = new Object();
                obj.name = copyArr[i].follow[j].name;
                obj.x = 1;
                obj.y = 1;
                obj.value = copyArr[i].follow[j].follower_count;
                obj.category = copyArr[i].name;
                obj.symbolSize = getWeiboUserSize(copyArr[i].follow[j].follower_count);
                obj.itemStyle = {
                    color: color[i % color.length]
                }
                if (nodeSet.has(copyArr[i].follow[j].name)) {

                }
                else {
                    nodeSet.add(copyArr[i].follow[j].name);
                    nodeOfUser.push(obj);
                }

                console.log("i=" + i + "   j=" + j);
            }

        }


        // 基于准备好的dom，初始化ECharts实例
        if (thisChart != null && thisChart != "" && thisChart != undefined) {
            thisChart.dispose();
        }
        thisChart = echarts.init(document.getElementById('div_level_2_force'), 'macarons');
        thisChart.showLoading();

        thisChart.setOption({
            series: [{
                type: 'graphGL',
                nodes: nodeOfUser,
                edges: links,
                categories: categories,
                lineStyle: {
                    color: 'rgba(0,0,0,0.5)'
                },
                itemStyle: {
                    opacity: 1
                },
                forceAtlas2: {
                    steps: 1,
                    stopThreshold: 1,
                    jitterTolerence: 10,
                    edgeWeight: [0.2, 1],
                    gravity: 0.1,
                    edgeWeightInfluence: 1,
                    scaling: 20,
                    preventOverlap: true
                },
                label: {
                    show: false,
                    position: 'bottom'

                }
            }]
        });

        thisChart.hideLoading();
    }
);


function loadLevel1MapGraph() {

    var listData = fullData.data.follow, userData = fullData.data.userInfo;

    //赋值给chart
    var thisChart = socialLevel2Map;
    //处理数据
    var copyArr = listData;//浅复制
    var convertData = [];
    var posMap = new Map();

    for (var i = 0; i < copyArr.length; i++) {
        if (copyArr[i].hometown.trim() != "") {
            var arr = copyArr[i].hometown.split(" ");
            var home = arr.length < 2 ? arr[0] : arr[1];
            var obj = new Object();
            obj.name = home;
            obj.value = CITYMAP.get(home);
            if (obj.value == undefined) {
                obj.value = [140.58, 50];
            }
            obj.symbol = 'circle';
            if (posMap.get(home) == undefined) {
                posMap.set(home, 1);
                obj.value.push(1);
            }
            else {
                posMap.set(home, (posMap.get(home) + 1));
                obj.value[2] = (posMap.get(home));
            }
            convertData.push(obj);
        }
        //第二层循环
        for (var j = 0; j < copyArr[i].follow.length; j++) {
            if (copyArr[i].follow[j].hometown.trim() != "") {
                var arr = copyArr[i].follow[j].hometown.split(" ");
                var home = arr.length < 2 ? arr[0] : arr[1];
                var obj = new Object();
                obj.name = home;
                obj.value = CITYMAP.get(home);
                if (obj.value == undefined) {
                    obj.value = [140.58, 50];
                }
                obj.symbol = 'circle';
                if (posMap.get(home) == undefined) {
                    posMap.set(home, 1);
                    obj.value.push(1);
                }
                else {
                    posMap.set(home, (posMap.get(home) + 1));
                    obj.value[2] = (posMap.get(home));
                }
                convertData.push(obj);
            }
            console.log("i=" + i + "   j=" + j);

        }
    }

    // 基于准备好的dom，初始化ECharts实例
    if (thisChart != null && thisChart != "" && thisChart != undefined) {
        thisChart.dispose();
    }
    thisChart = echarts.init(document.getElementById('div_level_1_map'), 'macarons');
    thisChart.showLoading();

    var option = {
        backgroundColor: '#404a59',
        title: {
            text: '博主' + userData.name + "的社交网络分布图",
            subtext: '热度越高的博主，颜色越深',
            x: 'center',
            textStyle: {
                color: '#fff'
            }
        },
        tooltip: {
            trigger: 'item',
            formatter: function (params) {
                return params.name + ' : ' + params.value[2];
            }
        },
        legend: {
            orient: 'vertical',
            y: 'bottom',
            x: 'right',
            data: ['粉丝'],
            textStyle: {
                color: '#fff'
            }
        },
        visualMap: {
            min: 0,
            max: 300,
            calculable: true,
            inRange: {
                color: ['#50a3ba', '#eac736', '#d94e5d']
            },
            textStyle: {
                color: '#fff'
            }
        },
        geo: {
            map: 'china',
            // roam: true,
            label: {
                emphasis: {
                    show: false
                }
            },
            itemStyle: {
                normal: {
                    areaColor: '#323c48',
                    borderColor: '#111'
                },
                emphasis: {
                    areaColor: '#2a333d'
                }
            }
        },
        series: [
            {
                name: '博主热度',
                type: 'scatter',
                roam: true,
                coordinateSystem: 'geo',
                data: convertData,
                symbolSize: 10,
                label: {
                    normal: {
                        show: false
                    },
                    emphasis: {
                        show: false
                    }
                },
                itemStyle: {
                    emphasis: {
                        borderColor: '#fff',
                        borderWidth: 1
                    }
                }
            }
        ]

    };
    thisChart.setOption(option);
    thisChart.hideLoading();
}

//情感分析
function weiboEmotion(uid) {

    var posArr = [];
    var negArr = [];

    getEmotion();

    function getEmotion() {


        //发送异步请求
        jQuery.ajax({
            url: weibo_emotion + uid,
            type: "get",
            dataType: "json",
            contentType: "application/json;charset=utf-8"
        }).done(function (res) {
            //将结果放进set里面
            for (var i = 0; i < res.data.res.length; i++) {
                posArr.push(res.data.res[i].classify[0].value);
                negArr.push(res.data.res[i].classify[1].value);
            }
            loadPie();


        }).fail(function (res) {
            layer.alert("请求失败", {icon: 7});
            layer.close(index);
        });
    }


    function loadPie() {
        var totalCount = 0;
        for (var i = 0; i < posArr.length; i++) {
            if (posArr[i] > negArr[i]) {
                totalCount++;
            }
        }
        console.log(totalCount);
        console.log(posArr.length);


        var emotionPieChart;
        loadEmotionPie(totalCount, (posArr.length - totalCount));


        function loadEmotionPie(pos, neg) {
            //赋值给chart
            var thisChart = emotionPieChart;


            // 基于准备好的dom，初始化ECharts实例
            if (thisChart != null && thisChart != "" && thisChart != undefined) {
                thisChart.dispose();
            }
            thisChart = echarts.init(document.getElementById('div_emotion_pie'), 'macarons');
            thisChart.showLoading();

            var piePatternSrc = '';


            var piePatternImg = new Image();
            piePatternImg.src = piePatternSrc;

            var itemStyle = {
                normal: {
                    opacity: 0.7,
                    color: {
                        image: piePatternImg,
                        repeat: 'repeat'
                    },
                    borderWidth: 3,
                    borderColor: '#235894'
                }
            };
            var option = {
                title: {
                    text: '情感极性图',
                    textStyle: {
                        color: '#235894'
                    }
                },
                tooltip: {},
                series: [{
                    name: '情感极性',
                    type: 'pie',
                    selectedMode: 'single',
                    selectedOffset: 30,
                    clockwise: true,
                    label: {
                        normal: {
                            textStyle: {
                                fontSize: 18,
                                color: '#235894'
                            }
                        }
                    },
                    labelLine: {
                        normal: {
                            lineStyle: {
                                color: '#235894'
                            }
                        }
                    },
                    data: [{"name": "正面情感", "value": pos}, {"name": "负面情感", "value": neg}],
                    itemStyle: itemStyle
                }]
            };


            thisChart.hideLoading();
            thisChart.setOption(option, true);
        }
    }


}



